/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.topology;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import nemos.remote.util.RemoteUtil;
import nemos.util.log.NemosLogger;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.EndpointListener;
import org.osgi.service.remoteserviceadmin.ImportRegistration;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin;

/**
 * ImportTopologyManager : The import-side of the topology manager.
 * 
 * <p>
 * This topology manager tries to import all remote endpoints.
 * </p>
 * 
 * @author Romain DUBOIS
 */
@Component
public class ImportTopologyManager implements EndpointListener {

    /** Registration : Remote listener */
    private ServiceRegistration<EndpointListener> mRegistration;

    /** Output : Remote service admins */
    @Reference(name = "rsa", referenceInterface = RemoteServiceAdmin.class, cardinality = ReferenceCardinality.MANDATORY_MULTIPLE, policy = ReferencePolicy.DYNAMIC)
    private final Collection<RemoteServiceAdmin> mRemoteServiceAdmins;
    /** The imported endpoint regsitrations */
    private final Map<EndpointDescription, ImportRegistration> mImportRegistrations;
    /** The logger */
    private NemosLogger mLogger;

    /**
     * Constructor
     */
    public ImportTopologyManager() {
        super();

        mRemoteServiceAdmins = Collections
                .synchronizedCollection(new ArrayList<RemoteServiceAdmin>());

        mImportRegistrations = Collections
                .synchronizedMap(new HashMap<EndpointDescription, ImportRegistration>());
    }

    /**
     * Import an endpoint into the local framework.
     * 
     * @param pEndpoint
     *            The endpoint to import
     */
    public void importEndpoint(final EndpointDescription pEndpoint) {

        // Check the endpoint is not already imported
        synchronized (mImportRegistrations) {
            if (mImportRegistrations.get(pEndpoint) != null) {
                return;
            }

            // Copy remote RSAs in order to minimize the synchronized block
            Collection<RemoteServiceAdmin> lRsaList;
            synchronized (mRemoteServiceAdmins) {
                lRsaList = new ArrayList<RemoteServiceAdmin>(mRemoteServiceAdmins);
            }

            // Try all RSAs until one imports successfully
            boolean lImportSuccessfull = false;
            final Iterator<RemoteServiceAdmin> lAdminsIt = lRsaList.iterator();
            while (lAdminsIt.hasNext() && !lImportSuccessfull) {
                final RemoteServiceAdmin lAdmin = lAdminsIt.next();

                lImportSuccessfull = importEndpoint(pEndpoint, lAdmin);
            }
        }
    }

    /**
     * Import an endpoint with a specific RSA.
     * 
     * @param pEndpoint
     *            The endpoint to import
     * @param pAdmin
     *            The RSA to use
     * @return If import succeeded
     */
    private boolean importEndpoint(final EndpointDescription pEndpoint,
            final RemoteServiceAdmin pAdmin) {
        // Try import
        ImportRegistration lRegistration = pAdmin.importService(pEndpoint);

        // Check it is a valid registration
        if (lRegistration != null) {
            if (lRegistration.getException() != null) {
                mLogger.error(TopologyMessage.IMPORT_FAILED, lRegistration.getException(),
                        pEndpoint.getId());
                lRegistration = null;
            }
        }

        // Register even null registrations for later RSAs
        mImportRegistrations.put(pEndpoint, lRegistration);

        return lRegistration != null;
    }

    /**
     * Stop the import of an endpoint in the local framework.
     * 
     * @param pEndpoint
     *            The imported endpoint
     */
    public void unimportEndpoint(final EndpointDescription pEndpoint) {
        final ImportRegistration lRegistration = mImportRegistrations.remove(pEndpoint);
        if (lRegistration != null) {
            lRegistration.close();
        }
    }

    /**
     * Start the component.
     * 
     * @param pContext
     *            The bundle context
     */
    @Activate
    public void start(final BundleContext pContext) {
        mLogger = new NemosLogger(ImportTopologyManager.class);

        // TODO : import on demand using EPL listener scope
        //
        // Listener and Find Hook services to detect bundles that have an
        // interest in specific services that potentially could be imported.

        final Dictionary<String, Object> lProps = new Hashtable<String, Object>();
        lProps.put(ENDPOINT_LISTENER_SCOPE, RemoteUtil.getRemoteEndpointFilter());
        mRegistration = pContext.registerService(EndpointListener.class, this, lProps);

        mLogger.setServiceReference(mRegistration.getReference());
    }

    /**
     * Stop the component.
     */
    @Deactivate
    public void stop() {
        mRegistration.unregister();
    }

    /**
     * Bind a new RSA service.
     * 
     * @param pRsa
     *            The new service
     */
    public void bindRsa(final RemoteServiceAdmin pRsa) {
        synchronized (mImportRegistrations) {
            // Local copy because of concurrent modifications
            final Collection<Entry<EndpointDescription, ImportRegistration>> lEntries = new ArrayList<Entry<EndpointDescription, ImportRegistration>>(
                    mImportRegistrations.entrySet());

            // Try to import known endpoints
            for (final Entry<EndpointDescription, ImportRegistration> lEntry : lEntries) {
                if (lEntry.getValue() == null) {
                    importEndpoint(lEntry.getKey(), pRsa);
                }
            }

            mRemoteServiceAdmins.add(pRsa);
        }
    }

    /**
     * Unbind a RSA service.
     * 
     * @param pRsa
     *            The service to unbind
     */
    public void unbindRsa(final RemoteServiceAdmin pRsa) {
        mRemoteServiceAdmins.remove(pRsa);
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.service.remoteserviceadmin.EndpointListener#endpointAdded(org.osgi.service.remoteserviceadmin.EndpointDescription,
     *      java.lang.String)
     */
    @Override
    public void endpointAdded(final EndpointDescription pEndpoint,
            @SuppressWarnings("unused") final String pMatchedFilter) {
        importEndpoint(pEndpoint);
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.service.remoteserviceadmin.EndpointListener#endpointRemoved(org.osgi.service.remoteserviceadmin.EndpointDescription,
     *      java.lang.String)
     */
    @Override
    public void endpointRemoved(final EndpointDescription pEndpoint,
            @SuppressWarnings("unused") final String pMatchedFilter) {
        unimportEndpoint(pEndpoint);
    }
}
